package com.zmm.member.service.impl;

import com.zmm.common.base.model.ResultCode;
import com.zmm.common.constant.NumberConstant;
import com.zmm.common.constant.StringConstant;
import com.zmm.common.dict.enums.RegionType;
import com.zmm.common.dict.enums.RegionVersion;
import com.zmm.common.dict.model.Region;
import com.zmm.common.enums.StringEnums;
import com.zmm.common.exception.handle.BusinessException;
import com.zmm.common.exception.handle.CustomRunTimeException;
import com.zmm.common.pre.handle.Assert;
import com.zmm.member.dao.CustomerAddressDao;
import com.zmm.member.model.CustomerAddress;
import com.zmm.member.service.CustomerAddressService;
import com.zmm.member.service.DictService;
import com.zmm.member.submit.vo.OrderAddressVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author 900045
 * @description:
 * @name CustomerAddressServiceImpl
 * @date By 2021-07-23 14:53:27
 */
@Service
public class CustomerAddressServiceImpl implements CustomerAddressService {
	
	@Resource
	private CustomerAddressDao customerAddressDao;
	
	@Resource
	private DictService dictService;

	/**
	 * 根据 用户ID 查询 用户地址列表 -- 实现
	 * @author: 900045
	 * @date: 2021-07-23 16:56:44
	 * @throws 
	 * @param customerId: 
	 * @return: java.util.List<com.zmm.member.submit.vo.OrderAddressVo>
	 **/
	@Override
	public List<OrderAddressVo> queryCustomerAddressListByCustomerId(Integer customerId) {
		List<OrderAddressVo> orderAddressVoList = customerAddressDao.selectCustomerAddressListByCustomerId(customerId);
		
		if (CollectionUtils.isEmpty(orderAddressVoList)){
			return null;
		}

		//地址格式化 参数格式化
		orderAddressVoList.forEach(orderAddressVo -> format(orderAddressVo) );
		return orderAddressVoList;
	}


	/**
	 * 用户添加 地址 -- 实现
	 * @author: 900045
	 * @date: 2021-08-04 16:40:21
	 * @throws 
	 * @param address: 
	 * @param customerId: 
	 * @return: boolean
	 **/
	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean addCustomerAddress(OrderAddressVo address, Integer customerId) throws BusinessException {
		Assert.notNull(address);
		checkValid(address.getProvinceId(), address.getCityId(), address.getCountyId(), address.getTownId());
		CustomerAddress customerAddress = this.packagingCustomerAddress(address, customerId);
		doSaveUpdate(customerAddress);
		return true;
	}

	/**
	 * 新增或者更新用户地址
	 * @author: 900045
	 * @date: 2021-08-04 16:39:12
	 * @throws 
	 * @param customerAddress: 
	 * @return: void
	 **/
	private void doSaveUpdate(CustomerAddress customerAddress) throws BusinessException{
		Integer save = 0;
		Integer update = 0;
		if (NumberConstant.ONE.equals(customerAddress.getWhetherDefault())){ 
			// 编辑或者新增时 如果用户设置了默认地址 先取消该用户的默认地址
			customerAddressDao.updateDefaultByCustomerId(customerAddress.getCustomerId());
		}

		if (null != customerAddress.getAddressId() && customerAddress.getAddressId() > 0) {
			// 修改
			update = customerAddressDao.updateCustomerAddress(customerAddress);
			if (update <= 0) {
				throw new BusinessException(ResultCode.CUSTOMER_ADDRESS_UPDATE_FAIL);
			}
		} else {
			// 判断该用户是否第一次添加地址
			CustomerAddress defaultAddress = customerAddressDao.searchCustomerAddressByCustomerIdAndDefault(customerAddress.getCustomerId(),
					NumberConstant.ONE);
			if (ObjectUtils.isEmpty(defaultAddress)) {
				// 将用户的第一个地址设置为 默认
				customerAddress.setWhetherDefault(StringEnums.DEFAULT.getCode());
			}
			save = customerAddressDao.saveCustomerAddress(customerAddress);
		}
		
		if (save <= 0) {
			throw new BusinessException(ResultCode.CUSTOMER_ADDRESS_INSERT_FAIL);
		}
		
	}

	/**
	 * 包装用户地址实体类
	 * @author: 900045
	 * @date: 2021-08-04 16:40:33
	 * @throws 
	 * @param address: 
	 * @param customerId: 
	 * @return: com.zmm.member.model.CustomerAddress
	 **/
	private CustomerAddress packagingCustomerAddress(OrderAddressVo address, Integer customerId) {
		CustomerAddress customerAddress = new CustomerAddress();
		if (null != address.getAddressId() && address.getAddressId() > 0) {
			customerAddress.setAddressId(address.getAddressId());
			customerAddress.setModifiedTime(System.currentTimeMillis());
		} else {
			customerAddress.setCreateTime(System.currentTimeMillis());
		}
		customerAddress.setConsigneeDetail(address.getConsigneeDetail());
		customerAddress.setConsigneeName(address.getConsigneeName());
		customerAddress.setConsigneeMobile(address.getConsigneeMobile());
		customerAddress.setConsigneePhone(address.getConsigneePhone());
		customerAddress.setConsigneeCountyId(address.getCountyId());
		customerAddress.setConsigneeProvinceId(address.getProvinceId());
		customerAddress.setConsigneeCityId(address.getCityId());
		customerAddress.setConsigneeTownId(address.getTownId());
		customerAddress.setConsigneePostcode(address.getConsigneePostcode());
		customerAddress.setCustomerId(customerId);
		customerAddress.setWhetherDefault(address.getWhetherDefault());
		customerAddress.setVersion(address.getVersion());
		return customerAddress;
	}

	/**
	 * 有效性校验
	 * @author: 900045
	 * @date: 2021-08-04 15:33:27
	 * @throws 
	 * @param consigneeProvince: 
	 * @param consigneeCity: 
	 * @param consigneeCounty: 
	 * @param consigneeTown: 
	 * @return: void
	 **/
	private void checkValid(Integer consigneeProvince, Integer consigneeCity, Integer consigneeCounty, Integer consigneeTown) {
		//校验地址有效性  ADDRESS_REGION_INVALID
		Region region = dictService.fetchRegion(RegionVersion.V2, RegionType.PROVINCE, 0, consigneeProvince);
		Assert.notNull(region, ResultCode.ADDRESS_REGION_INVALID);

		region = dictService.fetchRegion(RegionVersion.V2, RegionType.CITY, consigneeProvince, consigneeCity);
		Assert.notNull(region, ResultCode.ADDRESS_REGION_INVALID);

		region = dictService.fetchRegion(RegionVersion.V2, RegionType.DISTRICT, consigneeCity, consigneeCounty);
		Assert.notNull(region, ResultCode.ADDRESS_REGION_INVALID);

		if (region.getLeaf().byteValue() == StringConstant.HAS_SUB) {
			region = dictService.fetchRegion(RegionVersion.V2, RegionType.TOWN, consigneeCounty, consigneeTown);
			Assert.notNull(region, ResultCode.ADDRESS_REGION_INVALID);
		} else {
			if (consigneeTown != null && consigneeTown > 0) {
				throw new CustomRunTimeException(ResultCode.PARAMETER_ERROR, "town should be empty");
			}
		}

	}

	/**
	 * 地址格式化
	 * @author: 900045
	 * @date: 2021-08-04 15:31:24
	 * @throws 
	 * @param orderAddressVo: 
	 * @return: void
	 **/
	private void format(OrderAddressVo orderAddressVo) {
		RegionVersion regionVersion = RegionVersion.fetch(orderAddressVo.getVersion());

		// 省
		String province = dictService.fetchRegionName(regionVersion, RegionType.PROVINCE, 
												null, orderAddressVo.getProvinceId());
		orderAddressVo.setProvince(province);

		// 市
		String city = dictService.fetchRegionName(regionVersion, RegionType.CITY, 
													orderAddressVo.getProvinceId(), orderAddressVo.getCityId());
		orderAddressVo.setCity(city);

		// 区
		String county = dictService.fetchRegionName(regionVersion, RegionType.DISTRICT, 
													orderAddressVo.getCityId(), orderAddressVo.getCountyId());
		orderAddressVo.setCounty(county);
		if (regionVersion == RegionVersion.V2 && orderAddressVo.getTownId() != null) {
			// 街道
			String town = dictService.fetchRegionName(regionVersion, RegionType.TOWN, 
													orderAddressVo.getCountyId(), orderAddressVo.getTownId());
			orderAddressVo.setTown(town);
		}
	}
}
